<template>
    <div :class="['flex-wrapper', widthType === '1' && 'select-small', widthType === '3' && 'dialog-small']">
        <div class="flex" v-for="(item, index) in selectedCategories" :key="item.time">
            <el-select
                v-model="item.value[0]"
                class="zw-select-margin"
                :disabled="disabled"
                @change="val => firstHandler(val, index)"
                placeholder="一级类目"
                no-data-text="暂无可选类目">
                <el-option
                    v-for="item in item.list"
                    :key="item.categoryName"
                    :label="item.categoryName"
                    :value="item.categoryCode" />
            </el-select>
            <el-select
                v-model="item.value[1]"
                class="zw-select-margin"
                placeholder="二级类目"
                :disabled="disabled"
                @change="val => secondHandler(val, index)"
                no-data-text="请选择一级类目">
                <el-option
                    v-for="item in item.subList"
                    :disabled="item.disabled"
                    :key="item.categoryName"
                    :label="item.categoryName"
                    :value="item.categoryCode" />
            </el-select>
            <span class="del-span" v-if="index !== 0 && !disabled" @click="delSelectedCategories(index)">- 删除</span>
        </div>
        <span class="flex-span" v-if="!disabled" @click="addSelectedCategories">+ 添加</span>
    </div>
</template>
<script setup>
import { onMounted, reactive, watch } from 'vue';
import request from '@/request';
import { ElMessage } from 'element-plus';
const props = defineProps({
    widthType: {
        type: String,
        default: '2'
    },
    disabled: {
        type: Boolean,
        required: false,
        default: false
    },
    cateList: {
        type: Array,
        required: false,
        default: () => []
    }
});
const emit = defineEmits(['selectCategories']);
const selectedCategories = reactive([{ value: ['', ''], list: [], subList: [], time: new Date().getTime() }]);
//监听外部传递进来的的数据变化或者做初始化用
watch([() => props.cateList, () => selectedCategories[0].list], res => {
    if (res[0].length !== 0 && res[1].length !== 0) {
        let arr = res[0].reduce((res, cur) => {
            return res.concat([cur.categoriesSecondCode]);
        }, []);
        res[0].length !== 0 &&
            res[0].map((item, index) => {
                if (index === 0) {
                    selectedCategories[0].value = [item.categoriesFirstCode, item.categoriesSecondCode];
                    selectedCategories[0].subList = selectedCategories[0].list
                        .find(target => target.categoryCode === item.categoriesFirstCode)
                        .subList.map(goal => {
                            return {
                                ...goal,
                                disabled: delIndexArr(arr, item.categoriesSecondCode).includes(goal.categoryCode)
                                    ? true
                                    : goal.disabled
                                    ? goal.disabled
                                    : false
                            };
                        });
                } else {
                    selectedCategories.push({
                        value: [item.categoriesFirstCode, item.categoriesSecondCode],
                        list: selectedCategories[0].list,
                        subList: selectedCategories[0].list
                            .find(target => target.categoryCode === item.categoriesFirstCode)
                            .subList.map(goal => {
                                return {
                                    ...goal,
                                    disabled: delIndexArr(arr, item.categoriesSecondCode).includes(goal.categoryCode)
                                        ? true
                                        : goal.disabled
                                        ? goal.disabled
                                        : false
                                };
                            }),
                        time: new Date().getTime()
                    });
                }
            });
    }
});
// 删除数组中指定元素
const delIndexArr = (arr, target) => {
    let copyArr = [...arr];
    copyArr.splice(
        arr.findIndex(item => item === target),
        1
    );
    return copyArr;
};
// 初始化，获取类目数据
onMounted(async () => {
    if (props.widthType === '3') {
        const { data } = await request('miniappCategories');
        selectedCategories[0].list = data.list.map(item => {
            return {
                categoryCode: item.id,
                categoryName: item.name,
                subList: item.children.map(target => {
                    return {
                        categoryCode: target.id,
                        categoryName: target.name
                    };
                })
            };
        });
    } else {
        const { data } = await request('businessCateList');
        selectedCategories[0].list = data.list;
    }
});
/**
 *选择第一类目
 */
const firstHandler = (val, index) => {
    selectedCategories[index].subList = selectedCategories[index].list
        .find(item => val === item.categoryCode)
        .subList.map(target => {
            target.disabled = selectedCategories.some(cate => target.categoryCode === cate.value[1]);
            return target;
        });
    selectedCategories[index].value[1] = null;
    emit('selectCategories', []);
};
/**
 *选择第二类目
 */
const secondHandler = (val, index) => {
    if (selectedCategories.every(item => item.value[0] && item.value[1])) {
        emit(
            'selectCategories',
            selectedCategories.reduce((res, current) => {
                return res.concat({
                    categoriesFirst: current.value[0],
                    categoriesSecond: current.value[1],
                    categoriesFirstName: current.list.find(item => item.categoryCode === current.value[0]).categoryName,
                    categoriesSecondName: current.subList.find(item => item.categoryCode === current.value[1])
                        .categoryName
                });
            }, [])
        );
    }
    selectedCategories.map((item, idx) => {
        if (index !== idx) {
            item.subList = item.subList.map(target => {
                return {
                    ...target,
                    disabled: target.categoryCode === val ? true : target.disabled ? target.disabled : false
                };
            });
        }
    });
};
/**
 * 添加经营类目
 */
const addSelectedCategories = () => {
    if (props.disabled) return;
    let arr = selectedCategories.reduce((res, cur) => {
        return res.concat([cur.value[1]]);
    }, []);
    if (selectedCategories[0].list.every(item => item.subList.every(target => arr.includes(target.categoryCode)))) {
        ElMessage({
            type: 'error',
            message: '暂无可添加类目'
        });
        return;
    }
    emit('selectCategories', []);
    selectedCategories.push({ value: [], list: selectedCategories[0].list, subList: [], time: new Date().getTime() });
};
/** 删除经营类目*/
const delSelectedCategories = index => {
    if (props.disabled) return;
    let target = selectedCategories[index].value;
    selectedCategories.splice(index, 1);
    selectedCategories.map(item => {
        if (item.value[0] === target[0]) {
            item.subList = item.subList.map(sub => {
                return {
                    ...sub,
                    disabled: sub.categoryCode === target[1] ? false : sub.disabled ? sub.disabled : false
                };
            });
        }
    });
    if (selectedCategories.every(item => item.value[0] && item.value[1])) {
        emit(
            'selectCategories',
            selectedCategories.reduce((res, current) => {
                return res.concat({
                    categoriesFirst: current.value[0],
                    categoriesSecond: current.value[1],
                    categoriesFirstName: current.list.find(item => item.categoryCode === current.value[0]).categoryName,
                    categoriesSecondName: current.subList.find(item => item.categoryCode === current.value[1])
                        .categoryName
                });
            }, [])
        );
    }
};
</script>
<style lang="scss" scoped>
.flex-wrapper {
    position: relative;
    :deep(.el-input--suffix) {
        width: 216px !important;
    }
}
.select-small {
    :deep(.el-input--suffix) {
        width: 216px !important;
    }
}
.dialog-small {
    :deep(.el-input--suffix) {
        width: 231px !important;
    }
}
.zw-select-margin {
    margin-right: 8px;
}
.flex {
    display: flex;
    margin-bottom: 8px;
    position: relative;
}
.flex-span {
    font-size: 14px;
    font-weight: 400;
    color: #ff6b00;
    line-height: 40px;
    position: absolute;
    top: 0;
    right: -42px;
    cursor: pointer;
}
.del-span {
    font-size: 14px;
    font-weight: 400;
    line-height: 40px;
    position: absolute;
    color: #fe292b;
    top: 0;
    right: -42px;
    cursor: pointer;
}
</style>
